package com.gougou.front.web.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.gougou.common.util.CookieUtils;
import com.gougou.front.pojo.TbCart;
import com.gougou.front.pojo.TbUser;
import com.gougou.front.service.MPTbCartService;
import com.gougou.front.service.MPTbItemCatService;
import com.gougou.front.service.MPTbItemService;
import com.gougou.front.service.MPTbUserService;
import com.gougou.httpclient.service.HttpAPIService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONArray;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 购物车模块 前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2018-09-07
 */
@RestController
@RequestMapping("/tbCart")
public class TbCartController {

    @Autowired
    private MPTbCartService cartService;
    @Autowired
    private HttpAPIService apiService;
    @Autowired
    private MPTbUserService  userService;
    @Autowired
    private MPTbItemService itemService;
    @Autowired
    private MPTbItemCatService itemCatService;
    private static final String COOKIE_NAME = "TT_TOKEN";

    @RequestMapping(value = "list",method = RequestMethod.GET)
    public ModelAndView CartList(Long userId){
        ModelAndView mv = new ModelAndView("views/cart");

        EntityWrapper<TbCart> wr = new EntityWrapper<>();
        wr.where("user_id={0}",userId);
        List<TbCart> tbCarts = cartService.selectList(wr);

        mv.addObject("cartList",tbCarts);

        return mv;
    }

    /**
     * 商品添加到购物车
     * @param cart
     * @return
     */
    @RequestMapping(value = "/cart")
    public Long addCartItem(String cart,HttpServletRequest request){
        Date date = new Date();
        TbCart tbCart =null;
        try {
            JSONArray jsonArray =  new JSONArray(cart);
            for(int i=0;i<jsonArray.length(); i++){
                JSONObject object = jsonArray.getJSONObject(i);//将数组中的数据转为对象类型s
                tbCart= new TbCart();
                //得到的传入的json数据
                tbCart.setItemId(Long.valueOf(object.get("itemId").toString()));
                tbCart.setNum(Integer.parseInt(object.get("num").toString()));
                tbCart.setItemTitle(object.get("itemTitle").toString());
                tbCart.setItemImage(object.get("itemImage").toString());
                tbCart.setItemPrice(Long.parseLong(object.get("itemPrice").toString()));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        tbCart.setUserId(Long.valueOf(9));
        tbCart.setCreated(date);
        tbCart.setUpdated(date);
        //将数据保存如数据库
        cartService.insert(tbCart);

        return Long.valueOf(9);
    }

    //删除
    @RequestMapping(value = "delCart")
    public void delCart(Long id, HttpServletResponse resp) throws IOException {
        Boolean cartId;
        try{
            cartId = cartService.deleteById(id);
        }catch (Exception e){
            e.printStackTrace();
        }
        resp.sendRedirect("/tbCart/list?userId=9");
    }

    //删除多个
    @RequestMapping(value = "delAllProduct")
    public void delAllProduct(String itemid,HttpServletResponse resp) throws IOException {
        EntityWrapper<TbCart> wrapper = new EntityWrapper<>();
        //分割字符串
        itemid = itemid.substring(0,itemid.length()-1);
        String ids = itemid.replaceAll(",", " or item_id=");

        wrapper.where("id= "+ids);
        try {
            Boolean cartlist = cartService.delete(wrapper);
        }catch (Exception e){
            e.printStackTrace();
        }
        resp.sendRedirect("/tbCart/list?userId=9");
    }

    @RequestMapping(value = "Goorder")
    public ModelAndView ItemList(String itemid){
        ModelAndView mv = new ModelAndView("views/order");
        //截取字符串
        itemid = itemid.substring(0,itemid.length()-2);
        String ids = itemid.replaceAll(",", " or item_id=");
        //查询购物车
        EntityWrapper<TbCart> wr = new EntityWrapper<>();
        wr.where("item_id="+ids);
        List<TbCart> tbItems = cartService.selectList(wr);
        Integer sum = this.addNum(tbItems);
        Integer price = this.CountPrice(tbItems);
        //查询用户
        EntityWrapper<TbUser> user = new EntityWrapper<>();
        user.where("id={0}",8);
        TbUser users = userService.selectOne(user);

        mv.addObject("User",users);
        mv.addObject("CountPrice",price);
        mv.addObject("sum",sum);
        mv.addObject("ItemList",tbItems);

        return mv;
    }

    //计算数量
    public Integer addNum( List<TbCart> tbItems){
        Integer sum =0;

        for (TbCart cart :tbItems){
            sum+=cart.getNum();
        }


        return sum;
    }

    //计算总价
    public Integer CountPrice( List<TbCart> tbItems){
        Long price=null;
        Integer num =0;
        Integer count = 0;
        for (TbCart cart :tbItems){
            price = cart.getItemPrice();
            num =cart.getNum();

            count +=  Integer.valueOf(price.toString()) * num;
        }

        return count;
    }

    /**
     * 判断用户是否登陆，如果登陆将数据放入数据库，否则放入cookie
     * @return
     */
//    @RequestMapping(value="/cart",method = RequestMethod.GET)
//    public ModelAndView selUser(HttpServletRequest request){
//        ModelAndView mv = new ModelAndView("views/cart");
//
//        //获取session里的值,判断用户是否登陆
//        HttpSession session = request.getSession();
//        Object attribute = session.getAttribute(COOKIE_NAME);
//
//        if(null == attribute){
//            //未登陆状态,存cookie
//            Cookie[] cookies = request.getCookies();
//            for(int i = 0;i<cookies.length;i++){
//                Cookie cookie = cookies[i];
//                if(cookie.getName().equalsIgnoreCase("TT_TOKEN")){
//                    System.out.print("值："+cookie.getValue().toString());
//                }
//            }
//        }else{
//            //登陆状态
//            //得到用户编号
//
//            EntityWrapper<TbCart> wr = new EntityWrapper<>();
//            //wr.where("user_id={0}",);
//            //cartList = cartService.selectList(wr);
//
//        }
//
//        //mv.addObject("cartList",cartList);
//        return mv;
//    }

}